<template>
  <el-dialog
    :title="isEditing ? '编辑字段' : '添加字段'"
    v-model="dialogVisible"
    width="900px"
    top="5vh"
    @closed="handleDialogClosed"
    class="field-editor-dialog"
  >
    <el-form 
      :model="fieldForm" 
      :rules="rules" 
      ref="formRef" 
      label-width="120px"
      class="field-form"
    >
      <!-- 基础信息 -->
      <div class="form-section">
        <h4 class="section-title">基础信息</h4>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="显示名称" prop="name">
              <el-input 
                v-model="fieldForm.name" 
                placeholder="请输入显示名称" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="程序变量" prop="javaName">
              <el-input 
                v-model="fieldForm.javaName" 
                placeholder="请输入Java变量名" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="字段名" prop="columnName">
              <el-input 
                v-model="fieldForm.columnName" 
                placeholder="请输入数据库字段名" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数据类型" prop="dataType">
              <el-select 
                v-model="fieldForm.dataType" 
                placeholder="选择数据类型" 
                clearable
                class="full-width"
              >
                <el-option label="字符串" :value="1" />
                <el-option label="整数" :value="2" />
                <el-option label="浮点数" :value="5" />
                <el-option label="布尔值" :value="6" />
                <el-option label="日期" :value="9" />
                <el-option label="时间戳" :value="8" />
                <el-option label="JSON" :value="17" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="字段长度">
              <el-input-number 
                v-model="fieldForm.length" 
                :min="1" 
                :max="65535" 
                placeholder="字段长度"
                class="full-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="小数位数">
              <el-input-number 
                v-model="fieldForm.scale" 
                :min="0" 
                :max="30" 
                placeholder="小数位数"
                :disabled="![5].includes(fieldForm.dataType)"
                class="full-width"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 字段属性 -->
      <div class="form-section">
        <h4 class="section-title">字段属性</h4>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="是否必填">
              <el-switch 
                v-model="fieldForm.required" 
                :inactive-value="-1" 
                :active-value="1"
                active-text="必填"
                inactive-text="非必填"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否唯一">
              <el-switch 
                v-model="fieldForm.unique" 
                :inactive-value="0" 
                :active-value="1"
                active-text="唯一"
                inactive-text="非唯一"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否外键">
              <el-switch 
                v-model="fieldForm.foreignState" 
                :inactive-value="-1" 
                :active-value="1"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="持久化">
              <el-switch 
                v-model="fieldForm.persistent" 
                :inactive-value="-1" 
                :active-value="1"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否是明细集合">
              <el-switch 
                v-model="fieldForm.detailState" 
                :inactive-value="-1" 
                :active-value="1"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可以搜索">
              <el-switch 
                v-model="fieldForm.searchState" 
                :inactive-value="-1" 
                :active-value="1"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 关联模型 -->
      <div class="form-section" v-if="fieldForm.detailState === 1 || fieldForm.foreignState === 1">
        <h4 class="section-title">关联设置</h4>
        <!-- 明细集合关联模型选择 -->
        <el-row v-if="fieldForm.detailState === 1" :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联模型" prop="relatedModule">
              <el-select 
                v-model="fieldForm.relatedModule" 
                placeholder="请选择关联的模型"
                filterable
                clearable
                class="full-width"
              >
                <el-option
                  v-for="model in modelList"
                  :key="model.id"
                  :label="model.name"
                  :value="model.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 外键关联模型选择 -->
        <el-row v-if="fieldForm.foreignState === 1" :gutter="20">
          <el-col :span="24">
            <el-form-item label="外键关联模型" prop="relatedModule">
              <el-select 
                v-model="fieldForm.relatedModule" 
                placeholder="请选择外键关联的模型"
                filterable
                clearable
                class="full-width"
              >
                <el-option
                  v-for="model in modelList"
                  :key="model.id"
                  :label="model.name"
                  :value="model.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 其他设置 -->
      <div class="form-section">
        <h4 class="section-title">其他设置</h4>
        <el-form-item label="默认值">
          <el-input 
            v-model="fieldForm.defaultValue" 
            placeholder="请输入默认值" 
            clearable
          />
        </el-form-item>

        <el-form-item label="字段描述">
          <el-input 
            type="textarea" 
            v-model="fieldForm.comment" 
            :rows="3" 
            placeholder="请输入字段描述"
            show-word-limit
            maxlength="500"
          />
        </el-form-item>

        <el-form-item label="验证规则">
          <el-input 
            type="textarea" 
            v-model="fieldForm.validation" 
            :rows="2" 
            placeholder="请输入验证规则（如：min:1,max:100）"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" size="default">
          取消
        </el-button>
        <el-button type="primary" @click="saveField" size="default">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/utils/request.js'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  field: {
    type: Object,
    default: () => ({})
  },
  isEditing: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'save'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 表单引用
const formRef = ref(null)

// 字段表单数据
const fieldForm = ref(props.field)

// 模型列表
const modelList = ref([])

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入显示名称', trigger: 'blur' }
  ],
  javaName: [
    { required: true, message: '请输入程序变量名', trigger: 'blur' },
    { pattern: /^[a-zA-Z_$][a-zA-Z0-9_$]*$/, message: '程序变量名格式不正确', trigger: 'blur' }
  ],
  columnName: [
    { required: true, message: '请输入字段名', trigger: 'blur' },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '字段名格式不正确', trigger: 'blur' }
  ],
  dataType: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ],
  relatedModule: [
    { 
      validator: (rule, value, callback) => {
        if (fieldForm.value.detailState === 1 && !value) {
          callback(new Error('明细集合必须选择关联模型'))
        } else if (fieldForm.value.foreignState === 1 && !value) {
          callback(new Error('外键必须选择关联模型'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 保存字段
const saveField = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    emit('save', { ...fieldForm.value })
    dialogVisible.value = false
    ElMessage.success('字段保存成功')
  } catch (error) {
    ElMessage.warning('请填写必填项')
  }
}

// 获取模型列表
const fetchModelList = async () => {
  try {
    const res = await http.post('/moduleItem/list', {})
    if (res.code === 200) {
      modelList.value = res.data || []
    } else {
      ElMessage.error('获取模型列表失败')
    }
  } catch (error) {
    console.error('获取模型列表出错:', error)
    ElMessage.error('获取模型列表失败，请检查网络连接')
  }
}

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 组件挂载时获取模型列表
onMounted(() => {
  fetchModelList()
})
</script>

<style scoped>
.field-editor-dialog {
  --el-dialog-padding-primary: 20px;
}

.field-form {
  margin-top: 0;
}

.form-section {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 6px;
}

.full-width {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-switch) {
  --el-switch-on-color: #409eff;
  --el-switch-off-color: #dcdfe6;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}

:deep(.el-form-item) {
  margin-bottom: 14px;
}

:deep(.el-row) {
  margin-bottom: 0;
}

:deep(.el-col:last-child .el-form-item) {
  margin-bottom: 14px;
}
</style> 